package com.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.common.api.RouterPath;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.bkkp.AnalysisPojo;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.common.utils.MethodUtils;
import com.mine.adapter.ProfileOptionAdapter;
import com.mine.databinding.MineBinding;
import com.patch.AppUpdate;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;

@Route(path = RouterPath.MINE_MAIN)
public class MineFragment extends Fragment implements ProfileOptionAdapter.OnOptionClickListener {

    private MineBinding mineBinding;//视图绑定，避免使用R.id.xx有空的风险
    private ImageView profileImageView;
    private TextView usernameTextView;
    private TextView emailTextView;
    private TextView totalIncomeTextView;
    private TextView totalExpenseTextView;
    private TextView balanceTextView;
    private Button logoutButton;
    private RecyclerView optionsRecyclerView;
    private ProfileOptionAdapter adapter;
    private UserInfoPojo userInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mineBinding = MineBinding.inflate(inflater, container, false);
        initViews();
        setupProfileData();
        setupOptionsRecyclerView();
        setupListeners();

        //查询所有支出收入
        searchData();

        return mineBinding.getRoot();
    }

    private void initViews() {
        userInfo = JSONObject.parseObject(Constants.userInfo, UserInfoPojo.class);

        profileImageView = mineBinding.profileImage;
        usernameTextView = mineBinding.usernameText;
        emailTextView = mineBinding.emailText;
        totalIncomeTextView = mineBinding.totalIncomeText;
        totalExpenseTextView = mineBinding.totalExpenseText;
        balanceTextView = mineBinding.balanceText;
        logoutButton = mineBinding.logoutButton;
        optionsRecyclerView = mineBinding.optionsRecyclerView;
    }

    private void setupProfileData() {
        usernameTextView.setText(userInfo.getUsername());
        emailTextView.setText(userInfo.getEmail());
    }

    //查询所有支出收入
    private void searchData() {
        OkHttpUtils.get().url(ConstantsUrl.yearAnlysisUrl)
                .addParams("userId", userInfo.getId().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof java.net.SocketTimeoutException) {
                    showToast("网络连接超时，请检查网络设置");
                } else if (e instanceof java.io.IOException) {
                    showToast("网络请求失败，请检查网络连接");
                } else {
                    showToast("网络请求出现未知错误");
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Result result = null;
                try {
                    result = JSONObject.parseObject(response, Result.class);
                } catch (Exception e) {
                }
                if (result == null) {
                    result = Result.fail("请求返回失败");
                }
                if (result.getSuccess()) {
                    AnalysisPojo analysisPojo = JSONObject.parseObject(result.getData().toString(), AnalysisPojo.class);
                    requireActivity().runOnUiThread(() -> {
                        //总的支出收入结余
                        updateStatistics(analysisPojo);
                    });
                } else {
                    showToast(result.getMessage());
                }
            }
        });
    }

    //更新记账数据
    private void updateStatistics(AnalysisPojo analysisPojo) {
        if (isAdded() && getView() != null) { // 双重校验（可选）
            double balance = analysisPojo.getSurplus();
            // 设置记账数据
            totalIncomeTextView.setText(String.format("¥%.2f", analysisPojo.getIncome()));
            totalExpenseTextView.setText(String.format("¥%.2f", analysisPojo.getNsume()));
            balanceTextView.setText(String.format("¥%.2f", balance));
            balanceTextView.setTextColor(balance >= 0
                    ? Color.parseColor("#2196F3")
                    : Color.parseColor("#E12F2F"));
        }
    }

    private void setupOptionsRecyclerView() {
        optionsRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        List<ProfileOptionAdapter.ProfileOption> optionList = new ArrayList<>();

        // 添加记账APP特有的个人中心选项
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_category, "分类管理"));
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_calendar, "历史记录"));
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_security, "修改密码"));
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_setting, "账户设置"));
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_help, "帮助与反馈"));
        optionList.add(new ProfileOptionAdapter.ProfileOption(R.drawable.ic_version, "版本更新"));

        adapter = new ProfileOptionAdapter(optionList);
        adapter.setOnOptionClickListener(this);
        optionsRecyclerView.setAdapter(adapter);
    }

    private void setupListeners() {
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理退出登录逻辑
                logout();
            }
        });
    }

    private void logout() {
        new SweetAlertDialog(requireActivity(), SweetAlertDialog.WARNING_TYPE)
                .setTitleText("提示")
                .setContentText("是否退出登陆？")
                .setConfirmText("确定")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        // 实现退出登录的逻辑
                        SharedPreferences preferences = requireActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
                        preferences.edit().putString("userInfo", null).apply();
                        Constants.userInfo = null;
                        Intent intent = new Intent("com.pdd.SELECT_NAVIGATION_ITEM");
                        intent.putExtra("selectItemId", "logout");
                        getActivity().sendBroadcast(intent);
                    }
                })
                .setCancelText("取消")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onOptionClick(int position) {
        switch (position) {

            case 0: // 分类管理
                openCategoryManagement();
                break;
            case 1: // 历史记录
                openHistoryRecords();
                break;
            case 2: // 修改密码
                openChangePasswordPage();
                break;
            case 3: // 账户设置
                openSettings();
                break;
            case 4: // 帮助与反馈
                openHelpAndFeedback();
                break;
            case 5: //  版本更新
                AppUpdate.appUpdate(0, requireContext(), "com.ctaa", MethodUtils.getFilesDir(), ConstantsUrl.versionUrl);
                break;
        }
    }

    private void openFinancialStatistics() {
        // 打开财务统计页面
        showToast("暂无内容");
    }

    private void openCategoryManagement() {
        // 打开分类管理页面
        showToast("暂无内容");
    }

    private void openHistoryRecords() {
        // 打开历史记录页面
        showToast("暂无内容");
    }

    private void openChangePasswordPage() {
        // 打开修改密码页面
        Intent intent = new Intent(requireActivity(), ChangePasswordActivity.class);
        startActivity(intent);
    }

    private void openSettings() {
        // 打开账户设置页面
        showToast("暂无内容");
    }

    private void openHelpAndFeedback() {
        // 打开帮助与反馈页面
        showToast("暂无内容");
    }

    private void showToast(String content) {
        requireActivity().runOnUiThread(() -> {
            if (isAdded() && getView() != null) { // 双重校验（可选）
                Toast.makeText(requireContext(), content, Toast.LENGTH_SHORT).show();
            }
        });
    }
}